package orm

import (
	"fmt"
	"go-toy/util"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

// InitDB initializes the database connection using GORM and MySQL driver.
func init() {
	dbConfig := util.Viper.GetStringMap("db")

	if len(dbConfig) > 0 {
		// connection format: user:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local"
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", dbConfig["user"], dbConfig["password"], dbConfig["host"], dbConfig["port"], dbConfig["database"], dbConfig["charset"])

		// init database connection
		var err error
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
		if err != nil {
			panic("Failed to connect database:" + err.Error())
		}
		util.PrintlnSuccess("Successfully connected to database by DSN:\n - " + dsn)
	} else {
		util.PrintlnTrace("No database configuration found, skipping database initialization.")
	}
}
